// demo/measuring/measuring.js

const { QNMPPlugin, QNConsts } = requirePlugin("QNBleApi");
const wxPromise = require("../../../util/wxPromise.js");

// wxb0989a4bbce13d87为测试用appid, 记得切换为客户自己的
const APPID = 'wxb0989a4bbce13d87';

Page({
  /**
   * Page initial data
   */
  data: {
    age: 30,
    autoStopDiscovery: true,
    gender: "male",
    height: 170,
    isSport: false,
    unit: "kg",
    id: 0,
    realTimeWeight: 0,
    bleState: "空闲",
    state: "paused",
    measureData: null,
    score: 0,
    available: false,
    discovering: false,
    connected: false,
    connecting: false,
    wifiName: "",
    wifiPassword: "",
  },

  logger: () => {
    const wxlogger =
      wx.getLogManager &&
      wx.getLogManager({
        level: 0,
      });
    const log = (...params) => {
      console.log(...params);
      wxlogger && wxlogger.log(...params);
    };
    return {
      log,
    };
  },

  onLoad: function () {
    // 双模称才有配网功能
    this.initWifif()
    //初始化蓝牙
    this.bleApi = new QNMPPlugin({
      appId: APPID,
      logger: this.logger(),
    });

    this.bleApi.init();

    this.bleApi.onReady = ({
      bleEnableState, //表示当前蓝牙是否为开启状态
    }) => {
      // console.log("当前蓝牙状态",bleEnableState)
      if (bleEnableState) {   
        // this.bleApi.startBleDeviceDiscovery()
      } else {
        console.log("蓝牙状态为关闭");
      }
    };
    this.bleApi.setBleEventListener(this.bleEventListener());
  },

  onUnload: function () {
    this.stopBle();
  },
  initWifif() {
    this.satrtScanWifi();
  },
  stopBle: async function () {
    await this.bleApi.stop();
    await this.bleApi.releaseBleSource();
  },

  // 重置蓝牙
  restart() {
    this.bleApi
      .stop()
      .then(() => {
        this.setData({
          connected: false,
        });
        this.bleApi.startBleDeviceDiscovery();
      })
      .catch((err) => {
        console.log("停止扫描失败", err);
      });
  },

  async handlerConnect(device) {
    const { connected, wifiSsid, wifiPwd } = this.data;
    if (this.connecting || connected) {
      console.log("当前正在连接，不再处理");
      return;
    }
    this.connecting = true;
    /**
     * 调用连接成功后，会返回本次连接的设备访问对象，可以对设备进行一些蓝牙数据通讯
     * 每次连接返回的都不一样，连接成功后，该对象开始可以操作，连接失败或断开后，该对象会失效
     */

    this.deviceHandler = await this.bleApi.createBleConnection(
      device,
      this.deviceEventListener(),
      {
        action: QNConsts.QNBleAction.SET_WIFI, // 不支持5GHz频率的wif
        wifiSsid,
        wifiPwd, 
      }
    );

    console.log("设备方位对象为：", this.deviceHandler);
  },

  updateState(state) {
    this.setData({
      bleState: state,
    });
  },

  async satrtScanWifi() {
    wxPromise(wx.startWifi)()
      .then(res => {
        console.log("startWifi111", res);
        wx.getConnectedWifi({
          success: res => {
            console.log('getConnectedWifi', res)
            this.setData({
              wifiName: res.wifi.SSID,
            })
          },
          complete: res => {
            console.log('getConnectedWifi:complete', res)
          }
        })
        wx.onWifiConnected(res => {
          console.log("onWifiConnected", res);
          this.setData({
            wifiName: res.wifi.SSID,
          });
        });
      })
      .catch(err => {
        console.log("startWifi err", err);
      });
  },

  handlePasswordInput(e) {
    this.setData({
      wifiPassword: e.detail.value.trim(),
    });
  },

  async connectWifi() {
    const { wifiName, wifiPassword } = this.data;
    this.setData({
      wifiSsid: wifiName,
      wifiPwd: wifiPassword,
    })

    if (!wifiName) {
      this.toast("请先连接wifi");
    }
    if (!wifiPassword) {
      const modelResult = await wxPromise(wx.showModal)({
        title: "提示",
        content: "确定不需要密码吗？",
      });
      const { confirm } = modelResult;
      if (confirm) {
        this.startScan() // 开始扫描连接设备
      }
    } else {
      this.startScan() // 开始扫描连接设备
    }

  },

  startScan() {
    const { bluetoothEnabled } = wx.getSystemInfoSync();
    if (!bluetoothEnabled) {
      this.toast('请确认蓝牙是否开启');
      return
    }
    this.bleApi.startBleDeviceDiscovery()
    wx.showLoading({
      title: '配网中...',
    })
  },
  // 蓝牙相关事件回调
  bleEventListener() {
    /**
     * 监听扫描到设备的回调
     */
    const onBleDeviceFound = (device) => {
      this.handlerConnect(device);
    };

    /**
     * 监听蓝牙断开连接的回调
     */
    const onDisconnected = (device) => {
      this.updateState('设备连接已断开');
      this.setData({
        connected: false,
        state: 'paused',
        connecting: false,
      });
      this.connecting = false;
      this.connected = false;
      console.log('设备连接已断开', device);
    };

    /**
     * 监听蓝牙状态发生变化回调，连接成功或断开连接都会出触发
     */
    const onBluetoothEnableChange = ({ available }) => {};

    /**
     * 	监听设备连接成功回调
     */
    const onConnected = (device) => {
      this.updateState('已连接');
      console.log('设备已连接', device);
      this.connecting = false;
      this.setData({
        connected: true,
        device,
      });
    };

    /**
     * 监听停止扫描的回调
     */
    const onStopDiscoveryDevice = () => {
      this.updateState('已停止扫描');
      this.setData({
        discovering: false,
      });
    };

    /**
     * 监听开始扫描设备的回调
     */
    const onStartDiscoveryDevice = () => {
      this.updateState('开始扫描');
      this.setData({
        devices: [],
        discovering: true,
      });
    };

    return {
      onBleDeviceFound,
      onDisconnected,
      onBluetoothEnableChange,
      onConnected,
      onStopDiscoveryDevice,
      onStartDiscoveryDevice,
    };
  },

  // 秤端相关事件回调
  deviceEventListener() {
    /**
     * 实时测量体重
     */
    const onGetUnsteadyWeight = ({ weight }) => {};
    /**
     * 获取到了实时的稳定测量数据，在连接APP的情况下，进行测量，数据会进入到这个回调
     * @param {object} measure 体脂秤测量数据
     */
    const onGetScaleData = ({ measure }) => {};

    /**
     * 请求算法接口错误回调，一般是因为用户信息的参数错误导致
     */
    const onFetchScaleDataFail = (err) => {
      console.error('请求算法接口出错了', err);
    };

    /**
     * 回调配网结果
     */
    const onGetSetWifiResult = async (isSuccess) => {
      wx.hideLoading()
      if (isSuccess) {
        console.log("配网成功");
        this.updateState("配网成功");
      } else {
        console.log("配网失败");
        this.updateState("配网失败");
        this.toast("配网失败");
      }
      wx.showModal({
        title: "提示",
        content: isSuccess ? '配网成功' : '配网失败',
        showCancel: false,
        success () {
          // wx.navigateBack()
        }
      });
    }

    return {
      onGetUnsteadyWeight,
      onGetScaleData,
      onFetchScaleDataFail,
      onGetSetWifiResult,
    };
  },
  toast(str) {
    wx.showToast({
      icon: "none",
      title: str,
    });
  },
});
